package com.ebocy.hammer.world.handler;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import com.ebocy.hammer.core.GameCache;
import com.ebocy.hammer.core.constants.GameMessageCode;
import com.ebocy.hammer.core.domain.GamePlayer;
import com.ebocy.hammer.core.handler.IMessageHandler;
import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.message.IMessage;
import com.ebocy.hammer.core.service.GamePlayerService;
import com.ebocy.hammer.world.message.C2SJoin4V4RoomMessage;
import com.ebocy.hammer.world.message.C2SPlayerLogin;
import com.ebocy.hammer.world.service.TeamService;
import com.ebocy.hammer.world.service.WorldService;

/**
 * @author Qingrong Hou
 *
 *         May 15, 2012
 */
public class WorldHandler implements IMessageHandler {
	private static Logger logger = EbocyLogManager.getSystemLogger();
	private static short[] messageCodes = {
			GameMessageCode.HERT_BEAT,
			GameMessageCode.LOGIN,
			GameMessageCode.LOGOUT,
			GameMessageCode.WORLD_ENTER_4V4_ROOM,
			GameMessageCode.WORLD_QUIT_4V4_ROOM,
		};
	private WorldService worldService = WorldService.getInstance();
	private TeamService teamService = TeamService.getInstance();
	private GamePlayerService gamePlayerService = GamePlayerService.getInstance();
	private static WorldHandler worldHandler = null;

	private WorldHandler() {
	}

	public static WorldHandler getInstance() {
		if (worldHandler == null) {
			worldHandler = new WorldHandler();
		}
		return worldHandler;
	}

	@Override
	public short[] getMessageCodes() {
		return messageCodes;
	}

	@Override
	public void resolve(IMessage message, IoSession session) {
		GamePlayer gamePlayer = GameCache.getInstance().getGamePlayerBySession(session);
		switch (message.getMessageCode()) {
		case GameMessageCode.HERT_BEAT:
			if (gamePlayer != null) {
				gamePlayer.heartBeatTimestamp = System.currentTimeMillis();
			}
			break;
		case GameMessageCode.LOGIN:
			C2SPlayerLogin c2SPlayerLogin = (C2SPlayerLogin) message;
			worldService.login(c2SPlayerLogin, session);
			break;
		case GameMessageCode.WORLD_ENTER_4V4_ROOM:
			C2SJoin4V4RoomMessage enter4V4RoomMessage = (C2SJoin4V4RoomMessage)message;
			gamePlayer = gamePlayerService.getGamePlayerById(enter4V4RoomMessage.getPlayerId());
			gamePlayer.setSession(session);
			GameCache.getInstance().addGamePlayer(gamePlayer);
			teamService.enter4V4FightQueue(gamePlayer, enter4V4RoomMessage.getRoomId());
			break;
		case GameMessageCode.WORLD_QUIT_4V4_ROOM:
			teamService.quit4V4Queue(gamePlayer);
			break;
		case GameMessageCode.LOGOUT:
			gamePlayerService.exitGame(gamePlayer);
			break;
		default:
			logger.error("code" + message.getMessageCode() + "未处理！");
			break;
		}
	}
}
